﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.IO;

public partial class kecheng_confirm : System.Web.UI.Page
{
    private string s_where, s_order, sqlText;
    public string pics, texts;
    string curindex = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<string, string> userList = Application.Get("GLOBAL_USER_LIST") as Dictionary<string, string>;
        if (userList != null)
        {
            foreach (var item in userList)
            {
                if (item.Key != null && String.Compare(item.Key, Session.SessionID) == 0)
                {
                    if (item.Value != null && String.Compare("useronline", item.Value) == 0)
                    {
                        userList.Remove(Session.SessionID);
                        Application.Lock();
                        Application.Add("GLOBAL_USER_LIST", userList);
                        Application.UnLock();
                        Response.Write("<script type='text/javascript'>alert('您的账号已经在其他地方登录,您被强制下线');window.parent.location='index.aspx';</script>");
                        Response.End();
                    }
                    break;
                }
            }
        }
        Session["sTittle"] = "远程教育平台-我的首页";

        if (!IsPostBack)
        {
            getFlashImages();
            if (Session["sJigou"] == null)
            {
                Response.End();
            }
            string zjigou = Session["sJigou"].ToString().Trim();
            //我的课程 标记清楚其中session["sKecheng"],session["sKechenged"]的意义
            DataBrid();
            //机构课程
            //SqlDataSource5.SelectCommand = "SELECT  top 18 [id],[name] FROM [kecheng] WHERE [confirm]='终审通过' AND [jigou]='" + zjigou + "' ORDER BY [xtsj2] DESC";
            DataBridForOrg();
            //课程排行--报名人数最多的课程
            SqlDataSource6.SelectCommand = "select top 15 id,name from kecheng WHERE [confirm]='终审通过' AND ([jigou]='" + zjigou + "'or jigou='远程教育平台' or fabuzt='公开课程') order by datalength(xuesheng) desc";
            //老师排行榜--报名人数最多的老师
            //SqlDataSource3.SelectCommand = "SELECT top 18 [id],[username1] FROM [account] where role='老师' order by xtsj1 desc ";
            //SqlDataSource3.SelectCommand = "select username1,max(datalength(xuesheng)) from kecheng_laoshi group by username1 order by max(datalength(xuesheng)) desc";
            SqlDataSource3.SelectCommand = "select top 15 username1,max(datalength(xuesheng)) as id from kecheng_laoshi group by username1 order by max(datalength(xuesheng)) desc";
            SdsBBS.SelectCommand = "select top 8 f_title,title_id from [bbs_for_kecheng] where (f_dep='" + Session["sJigou"].ToString() + "') and f_subbbs=3 and f_layer=1 and f_topic like '%80002%' order by  f_imp desc,f_date desc";
            //SdsBBS.SelectCommand = "select top 7 f_title,title_id from [bbs_for_kecheng] where (f_dep='远程教育平台' or f_dep='" + Session["sJigou"].ToString() + "') and f_subbbs=3 and f_layer=1 and f_topic like '%80002%' order by  f_imp desc,f_date desc";
            //课程、老师排行榜通用的处理程序
            string zconnectionstr = WebConfigurationManager.ConnectionStrings["gConnectionString"].ConnectionString;
            string zsql = string.Format("Select top 15 laoshi,username,username1,xuesheng,id,name from kecheng_laoshi WHERE [confirm]='终审通过' AND ([jigou]='" + zjigou + "'{0}) order by datalength(xuesheng) desc", kechengPeizhi() ? "or fabuzt='公开课程'" : "");
            SqlDataAdapter dadPaihang = new SqlDataAdapter(zsql, zconnectionstr);
            DataTable dtPaihang = new DataTable();
            dadPaihang.Fill(dtPaihang);

            //以下向排行表中添加两个字段：
            dtPaihang.Columns.Add("f_count", typeof(int));  //报名人数
            dtPaihang.Columns.Add("f_disp", typeof(bool));

            //以下添加关键字
            DataColumn[] zkey = new DataColumn[1];
            zkey[0] = dtPaihang.Columns["id"];
            dtPaihang.PrimaryKey = zkey;
            //重新整理dtPaihang
            string zlist = "";  //缓存名单
            string zxuesheng = "";
            for (int i = 0; i < dtPaihang.Rows.Count; i++)  //取得每行的精确报名人数
            {
                zxuesheng = dtPaihang.Rows[i]["xuesheng"].ToString();  //取得报名的列表，用来计算报名人数
                dtPaihang.Rows[i]["f_count"] = (zxuesheng.Length - zxuesheng.Replace(",,", "").Length) / 2;
            }
            DataView dvPaihang = dtPaihang.DefaultView;
            dvPaihang.Sort = "f_count desc";
            GridView6.DataSourceID = null;
            GridView6.DataSource = dvPaihang;
            GridView6.DataBind();
            DataTable dtPingtai1 = new DataTable();
            dtPingtai1 = dtPaihang.Clone();

            string zusernameList = "";
            string zid;
            DataRow zdr;
            for (int i = 0; i <= GridView6.Rows.Count - 1; i++)
            {
                zid = GridView6.DataKeys[i].Value.ToString();
                zdr = dtPaihang.Rows.Find(zid);
                if (zusernameList.IndexOf("," + zdr["username"].ToString() + ",") < 0)
                {
                    dtPingtai1.Rows.Add(zdr.ItemArray);
                    zusernameList += "," + zdr["username"].ToString() + ",";
                }

            }
            DataView dvPaihang_laoshi = dtPingtai1.DefaultView;
            GridView3.DataSourceID = null;
            GridView3.DataSource = dvPaihang_laoshi;
            GridView3.DataBind();
        }
    }

    protected void GdvBBS_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string zid = e.CommandArgument.ToString();  //取得title_id
        string zscript = "bbs/contentview.aspx?mode=2&title_id=" + zid + "&forum_id=80002";
        zxd_content("3");
        Response.Redirect(zscript, true);
    }

    protected void GdvBBS1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string zid = e.CommandArgument.ToString();  //取得title_id
        string zscript = "bbs/contentview.aspx?mode=2&title_id=" + zid + "&forum_id=80002";
        zxd_content("4");
        Response.Redirect(zscript, true);
    }

    protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }
    }
    protected void GridView4_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            e.Row.Cells[0].Text = (e.Row.RowIndex + (Pager.PageSize * (Pager.CurrentPageIndex - 1) + 1)).ToString();
        }
        if (Session["sRole"].ToString() == "学员" & e.Row.RowIndex != -1)
        {
            string zid = "," + GridView4.DataKeys[e.Row.RowIndex]["id"].ToString() + ",";
            if (Session["sKecheng"].ToString().IndexOf(zid) >= 0 | Session["sKechenged"].ToString().IndexOf(zid) >= 0)
            {
                e.Row.Cells[0].ForeColor = System.Drawing.Color.Red;
            }
        }
    }
    protected void GridView5_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            e.Row.Cells[0].Text = (e.Row.RowIndex + (Pager2.PageSize * (Pager2.CurrentPageIndex - 1) + 1)).ToString();
        }
        if (Session["sRole"].ToString() == "学员" & e.Row.RowIndex != -1)
        {
            string zid = "," + GridView5.DataKeys[e.Row.RowIndex]["id"].ToString() + ",";
            if (Session["sKecheng"].ToString().IndexOf(zid) >= 0 | Session["sKechenged"].ToString().IndexOf(zid) >= 0)
            {
                e.Row.Cells[0].ForeColor = System.Drawing.Color.Red;
            }
        }
    }

    protected void GridView6_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }
    }

    protected string zxdtransform(string zs1)   //由 Session["sKecheng"], Session["sKechenged"], Session["sKecheng_Voted"] 此方法还会用在学生已学章节上.
    {
        string zxdstring = "[id]=";
        //string zs1 = Session["sKecheng"].ToString();
        if (zs1.Length >= 2)    //如果参数zs1是空的，则返回“ ”，并退出程序。否则生成形如id=id1...id=id?的字符串
        {
            zs1 = zs1.Substring(2); //去掉前2个“,,”。
        }
        else
        {
            return "1=2";
        }
        int i = zs1.IndexOf(",,");
        while (i > 0)
        {
            zxdstring = zxdstring + zs1.Substring(0, i) + " OR [id]=";
            zs1 = zs1.Substring(i + 2);
            i = zs1.IndexOf(",,");
        }
        i = zs1.IndexOf(",");
        zxdstring = zxdstring + zs1.Substring(0, i);
        return zxdstring ;
    }
    protected void GdvBBS_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }
    }
    private void zxd_content(string subBbs)
    {
        Session["CPage"] = 1;
        Session["sTittle"] = "平台信息交流";    //用Session["sTittle"] 标示当前程序功能，在masterpage中显示标题。周晓东2008-2-21
        if ((Session["sRole"].ToString() == "机构") | (Session["sRole"].ToString() == "管理员"))
            Session["dutyno"] = "99";
        else if (Session["sRole"].ToString() == "老师")
            Session["dutyno"] = "5";
        else
            Session["dutyno"] = "1";

        Conn conn = new Conn();

        Session["userno"] = conn.sqlFirst("select id from account where username='" + Session["sUserName"].ToString() + "'");

        Session["dep"] = Session["sJigou"].ToString();
        Session["dep1"] = Session["dep"].ToString();
        Session["subbbsid"] = subBbs;

        conn.Dispose();
        //----从搜索页面点左侧栏目菜单，需要把数据集的session变量置空，以便重新加载数据集
        if (!Page.IsPostBack)
        {
            Session["dv_content"] = null;
        }
    }
    /// <summary>
    /// 动态获取首页展示flash图片
    /// </summary>
    /// <returns></returns>
    public void getFlashImages()
    {

        string sql = string.Format("select id from JiGouPeiZhi where JiGouMingCheng='{0}'", Session["sJigou"].ToString());
        string id = string.Empty;
        object obj = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
        if (obj != null)
        {
            id = obj.ToString();
        }
        if (id != string.Empty)
        {
            sql = string.Format("select TOP 6 LuJing,font_img from TuPianKu where JiGouBiaoZhiFu='{0}' and visible = '{1}' order by img_order desc", id, "1");
            SqlDataReader dr = DbHelper.ExecuteReader(CommandType.Text, sql, null);
            if (dr.HasRows)
            {
                string images = string.Empty;
                string tes = string.Empty;
                while (dr.Read())
                {
                    images += dr["LuJing"].ToString().Replace("../", "") + "|";
                    tes += dr["font_img"].ToString().Replace("../", "") + "|";
                }
                dr.Close();
                images = images.Remove(images.Length - 1);
                pics = images;
                texts = tes;
            }
            else
            {
                pics = "picture/aaa.jpg|picture/bbb.jpg|picture/ccc.jpg|picture/ddd.jpg|picture/eee.jpg";
                texts = "aaa|bbb|ccc|ddd|eee";
            }
        }
        else
        {
            pics = "picture/aaa.jpg|picture/bbb.jpg|picture/ccc.jpg|picture/ddd.jpg|picture/eee.jpg";
            texts = "aaa|bbb|ccc|ddd|eee";
        }
    }
    /// <summary>
    /// 获取机构内课程配置
    /// </summary>
    /// <returns></returns>
    public bool kechengPeizhi()
    {
        string sql = string.Format("select kecheng from JiGouPeiZhi where JiGouMingCheng='{0}'", Session["sJigou"].ToString());
        object obj = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
        if (obj != null)
        {
            if (obj.ToString() == "1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
       
    }
    /// <summary>
    /// 获取机构内老师配置
    /// </summary>
    /// <returns></returns>
    public bool laoshiPeizhi()
    {
        string sql = string.Format("select laoshi from JiGouPeiZhi where JiGouMingCheng='{0}'", Session["sJigou"].ToString());
        string tag = string.Empty;
        object obj = DbHelper.ExecuteScalar(CommandType.Text, sql, null);
        if (obj != null)
        {
            return true;
        }
        else
        {
            return false;
        }
      
    }

    private void DataBrid()
    {
        string role = Session["sRole"].ToString().Trim();
        switch (role)
        {
            case "学员":
                DataBrid2();
                break;
            case "老师":
                DataBrid1();
                break;
            case "机构":
                DataBrid3();
                break;
            case "远程教育平台":
                DataBrid4();
                break;
            case "管理员":
                DataBrid4();
                break;
        }
    }

    private void DataBrid1()
    {
        int record = 0;
        int count = 0;
        string zusername = Session["sUserName"].ToString().Trim();
        s_order = "ORDER BY [xtsj2] DESC";
        s_where = "[kecheng] where [laoshi] = '" + zusername + "' or writer='" + zusername + "'";
        sqlText = "[id], [name]";
        DataTable DT = DbHelper.ExecutePage(sqlText, s_where, "id", s_order, Pager.CurrentPageIndex, Pager.PageSize, out record, out count, null);
        Pager.RecordCount = record;
        this.GridView4.DataSource = DT;
        this.GridView4.DataBind();
    }

    private void DataBridForOrg()//机构课程绑定数据
    {
        int record = 0;
        int count = 0;
        string jigou = Session["sJigou"].ToString().Trim();
        s_order = "ORDER BY [xtsj2] DESC";
        s_where = "[kecheng] where [confirm] = '终审通过' and [jigou] = '" + jigou + "'";
        sqlText = "[id], [name]";
        DataTable DT = DbHelper.ExecutePage(sqlText, s_where, "id", s_order, Pager2.CurrentPageIndex, Pager2.PageSize, out record, out count, null);
        Pager2.RecordCount = record;
        this.GridView5.DataSource = DT;
        this.GridView5.DataBind();
    }

    private void DataBrid2()
    {
        int record = 0;
        int count = 0;
        string zxd1 = "";
        string noth = Session["sKecheng"].ToString();
        zxd1 = zxdtransform(noth);
        string zxd2 = "";
        noth = Session["sKechenged"].ToString();
        zxd2 = zxdtransform(noth);
        txtzxd1.Text = "SELECT [id], [name] FROM [kecheng] WHERE " + zxd1;
        txtzxd2.Text = "SELECT [id], [name] FROM [kecheng] WHERE " + zxd2;
        //SqlDataSource4.SelectCommand = txtzxd1.Text.Trim();
        s_order = "ORDER BY [xtsj2] DESC";
        s_where = "[kecheng] where " + zxd1;
        sqlText = "[id], [name]";
        DataTable DT = DbHelper.ExecutePage(sqlText, s_where, "id", s_order, Pager.CurrentPageIndex, Pager.PageSize, out record, out count, null);
        Pager.RecordCount = record;
        this.GridView4.DataSource = DT;
        this.GridView4.DataBind();
    }

    private void DataBrid3()
    {
        int record = 0;
        int count = 0;
        string zjigou = Session["sJigou"].ToString().Trim();
        s_order = "ORDER BY [xtsj2] DESC";
        s_where = "[kecheng] where [jigou] = '" + zjigou + "'";
        sqlText = "[id], [name]";
        DataTable DT = DbHelper.ExecutePage(sqlText, s_where, "id", s_order, Pager.CurrentPageIndex, Pager.PageSize, out record, out count, null);
        Pager.RecordCount = record;
        this.GridView4.DataSource = DT;
        this.GridView4.DataBind();
    }

    private void DataBrid4()
    {
        int record = 0;
        int count = 0;
        s_order = "ORDER BY [xtsj2] DESC";
        s_where = "[kecheng] where 1=1";
        sqlText = "[id], [name]";
        DataTable DT = DbHelper.ExecutePage(sqlText, s_where, "id", s_order, Pager.CurrentPageIndex, Pager.PageSize, out record, out count, null);
        Pager.RecordCount = record;
        this.GridView4.DataSource = DT;
        this.GridView4.DataBind();
    }

    //李红新更改 2010-09-17 条件绑定数据
    private void DataBrid(string sqlwhere)
    {
        int record = 0;
        int count = 0;
        s_order = "ORDER BY [xtsj2] DESC";
        sqlText = "[id], [name]";
        DataTable DT = DbHelper.ExecutePage(sqlText, "[kecheng]" + sqlwhere, "xtsj2", s_order, Pager.CurrentPageIndex, Pager.PageSize, out record, out count, null);
        Pager.RecordCount = record;
        this.GridView4.DataSource = DT;
        this.GridView4.DataBind();
    }

    protected void pager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        Pager.CurrentPageIndex = e.NewPageIndex;
        if (ViewState["sqlwhere"] != null)
        {
            DataBrid(ViewState["sqlwhere"].ToString());
        }
        else
        {
            HideOrg.Value = "0";
            DataBrid();
        }
    }

    protected void pager_PageChanging2(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        Pager2.CurrentPageIndex = e.NewPageIndex;
        if (ViewState["sqlwhere"] != null)
        {
            DataBrid(ViewState["sqlwhere"].ToString());
        }
        else
        {
            HideOrg.Value = "1";
            DataBridForOrg();
        }
    }

    public static string CutString(string inputString)
    {
        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        int len = 25;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }

            if (tempLen > len)
                break;
        }
        //如果截过则加上个省略号
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (mybyte.Length > len)
            tempString += "...";
        return tempString;
    }



}
